home *** CD-ROM | disk | FTP | other *** search
/ Power Programmierung / Power-Programmierung (Tewi)(1994).iso / magazine / pctchnqs / 1991 / number3 / l1.c < prev    next >
Text File  |  1991-05-28  |  2KB  |  73 lines

  1. /* Word counting program.  Tested with Borland C++ 2.0 in C
  2.    compilation mode and the small model */
  3.  
  4. #include <stdio.h>
  5. #include <fcntl.h>
  6. #include <sys\stat.h>
  7. #include <stdlib.h>
  8. #include <io.h>
  9.  
  10. #define BUFFER_SIZE  0x8000   /* largest chunk of file worked
  11.                                  with at any one time */
  12. int main(int, char **);
  13.  
  14. int main(int argc, char **argv) {
  15.    int Handle;
  16.    unsigned int BlockSize;
  17.    long FileSize;
  18.    unsigned long WordCount = 0;
  19.    char *Buffer, CharFlag = 0, PredCharFlag, *BufferPtr, Ch;
  20.  
  21.    if (argc != 2) {
  22.       printf("usage: wc <filename>\n");
  23.       exit(1);
  24.    }
  25.  
  26.    if ((Buffer = malloc(BUFFER_SIZE)) == NULL) {
  27.       printf("Can't allocate adequate memory\n");
  28.       exit(1);
  29.    }
  30.  
  31.    if ((Handle = open(argv[1], O_RDONLY | O_BINARY)) == -1) {
  32.       printf("Can't open file %s\n", argv[1]);
  33.       exit(1);
  34.    }
  35.  
  36.    if ((FileSize = filelength(Handle)) == -1) {
  37.       printf("Error sizing file %s\n", argv[1]);
  38.       exit(1);
  39.    }
  40.  
  41.    /* Process the file in chunks */
  42.    while (FileSize > 0) {
  43.       /* Get the next chunk */
  44.       FileSize -= (BlockSize = min(FileSize, BUFFER_SIZE));
  45.       if (read(Handle, Buffer, BlockSize) == -1) {
  46.          printf("Error reading file %s\n", argv[1]);
  47.          exit(1);
  48.       }
  49.       /* Count words in the chunk */
  50.       BufferPtr = Buffer;
  51.       do {
  52.          PredCharFlag = CharFlag;
  53.          Ch = *BufferPtr++ & 0x7F; /* strip high bit, which some
  54.                                       word processors set as an
  55.                                       internal flag */
  56.          CharFlag = ((Ch >= 'a') && (Ch <= 'z')) ||
  57.                     ((Ch >= 'A') && (Ch <= 'Z')) ||
  58.                     ((Ch >= '0') && (Ch <= '9')) ||
  59.                     (Ch == '\'');
  60.          if ((!CharFlag) && PredCharFlag) {
  61.             WordCount++;
  62.          }
  63.       } while (--BlockSize);
  64.    }
  65.  
  66.    /* Catch the last word, if any */
  67.    if (CharFlag) {
  68.       WordCount++;
  69.    }
  70.    printf("\nTotal words in file: %lu\n", WordCount);
  71.    return(0);
  72. }
  73.